package com.ddxz.csms.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2021/11/20
 */

@Configuration
@MapperScan(basePackages = "com.ddxz.csms.mapper.run", sqlSessionTemplateRef = "runSessionTemplate")
public class DataShenTongConfig {
    @Bean("runDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.run")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    @Bean("runMysqlSessionFactory")
    public SqlSessionFactory baseMysqlSessionFactory(@Qualifier("runDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        Interceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();

        properties.setProperty("helperDialect", "postgresql");
        properties.setProperty("reasonable", "false");
        interceptor.setProperties(properties);
        factoryBean.setPlugins(interceptor);
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/run/DataMapper.xml"));
        return factoryBean.getObject();
    }

    @Bean("runTranscationManager")
    public DataSourceTransactionManager baseTranscationManager(@Qualifier("runDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("runSessionTemplate")
    public SqlSessionTemplate baseSessionTemplate(@Qualifier("runMysqlSessionFactory") SqlSessionFactory factory) {
        return new SqlSessionTemplate(factory);
    }
}
